#include "StdAfx.h"
#include "VSqlGenId.h"

// VSqlQuery //////////////////////////////////////////////////////////////////

//
bool VSqlQuery::exec(const QString &query)
{
	bool ret = QSqlQuery::exec(query);
	if (!VSqlLog_script::canWrite())
		return ret;

	VSqlLog_script::write(query);
	return ret;
}

//
bool VSqlQuery::exec()
{
	bool ret = QSqlQuery::exec();
	if (!VSqlLog_script::canWrite())
		return ret;
		
	if (!isSelect())
	{
		QString sql = lastQuery();
		replaceParams(sql);
		VSqlLog_script::write(sql);
	}
	
	return ret;
}

//
bool VSqlQuery::next()
{
	bool ret = QSqlQuery::next();
	if (!VSqlLog_script::canWrite())
		return ret;

	if (!ret && QSqlQuery::size() > 0)
		return ret;

/*********
if (!ret)		
{
	ret=ret;
}
*********/

	QString sql = lastQuery();
	QString s = "--" + sql;
	replaceParams(sql);
	s += "\r\n" + sql + "\r\n--";
	
	QSqlRecord rec = record();
	for (int i = 0; i < rec.count(); ++i)
	{
		const QSqlField field = rec.field(i);
		s += field.name() + "=" + field.value().toString() + ",";
	}
	
	VSqlLog_script::write(s);
		
	return ret;
}

//
void VSqlQuery::replaceParams(QString &sql) const
{
	QMapIterator<QString,QVariant> i(boundValues());
	while (i.hasNext()) 
	{
		i.next();

		QString param = i.key();
		//QString pExpr = ":+( +)*" + param.remove(QChar(':'));
		QString pExpr = ":\\b" + param.remove(QChar(':')) + "\\b";
		QString value = i.value().isNull() ? "null" : "'" + i.value().toString() + "'";

		sql.replace(QRegExp(pExpr),value);
	}
}

// VSqlGenId //////////////////////////////////////////////////////////////////

//
VSqlGenId::VSqlGenId(const QSqlDatabase& db)
	:m_query(db) 
{
	bool ret = m_query.prepare(
		"execute procedure VidGenId"
	);

	if (VSqlLog::canWrite())
		VSqlLog::write("VSqlGenId::VSqlGenId",m_query.lastQuery());

	Q_ASSERT(ret == true);
}

//
QVariant VSqlGenId::exec()
{
	bool isOk = m_query.exec();
	Q_ASSERT(isOk == true);
	isOk = m_query.next();
	Q_ASSERT(isOk == true);

	return m_query.record().value("id");
}
